<?php
class StandardView
{
    /**
     * The passed querystring variables
     *
     * @var array[string]mixed
     */
    private $_get;
    /**
     * The db class that provides access to the database
     *
     * @var Db
     */
    private $_db;
    /**
     * The html class that provides helpers to display the text
     *
     * @var Html
     */
    private $_html;
    /**
     * The page title
     *
     * @var string
     */
    private $_pageTitle;
    /**
     * Store styles to be loaded
     *
     * @var array[int]string
     */
    private $_style;
    /**
     * Store scripts to be loaded
     *
     * @var array[int]string
     */
    private $_script;
    /**
     * Show the left bar section
     *
     * @var bool
     */
    private $_showLeftBar;
    /**
     * Show the ad bar section
     *
     * @var bool
     */
    private $_showAdBar;
    /**
     * Show the featurebar bar section
     *
     * @var bool
     */
    private $_showFeatureBar;
    /**
     * Show an alternate header with the persons name
     *
     * @var bool
     */
    private $_showPersonalHeader;
    /**
     * Set the title of the page
     *
     * @return void
     * @param string $title
     */
    public function setTitle($title)
    {
        $this->_pageTitle = $title;
    }
    /**
     * Add a style to the page
     *
     * @return void
     * @param string $source
     */
    public function style($source)
    {
        $this->_style[] = $source;
    }
    /**
     * Add a script to the page
     *
     * @return void
     * @param string $source
     */
    public function script($source)
    {
        $this->_script[] = $source;
    }
    /**
     * Show the header with the persons name
     *
     * @return void
     * @param bool $show
     */
    public function showPersonalHeader($show=TRUE)
    {
        $this->_showPersonalHeader = $show;
    }
    /**
     * Show the normal header
     *
     * @return void
     * @param bool $hide
     */
    public function hidePersonalHeader($hide=TRUE)
    {
        $this->showPersonalHeader(!$hide);
    }
    /**
     * Show the normal header
     *
     * @return void
     * @param bool $show
     */
    public function showNormalHeader($show=TRUE)
    {
        $this->showPersonalHeader(!$show);
    }
    /**
     * Show the left bar
     *
     * @return void
     * @param bool $show
     */
    public function showLeftBar($show=TRUE)
    {
        $this->_showLeftBar = $show;
    }
    /**
     * Prevent the left bar from being shown
     *
     * @return void
     * @param bool $hide
     */
    public function hideLeftBar($hide=TRUE)
    {
        $this->showLeftBar(!$hide);
    }
    /**
     * Show the ads section
     *
     * @return void
     * @param bool $show
     */
    public function showAdBar($show=TRUE)
    {
        $this->_showAdBar = $show;
    }
    /**
     * Hide the ads section
     *
     * @return void
     * @param bool $hide
     */
    public function hideAdBar($hide=TRUE)
    {
        $this->showAdBar(!$hide);
    }
    /**
     * Show the feature bar section
     *
     * @return void
     * @param bool $show
     */
    public function showFeatureBar($show=TRUE)
    {
        $this->_showFeatureBar = $show;
    }
    /**
     * Hide the feature bar section
     *
     * @return void
     * @param bool $hide
     */
    public function hideFeatureBar($hide=TRUE)
    {
        $this->showFeatureBar(!$hide);
    }
    /**
     * Builds the list of text messages
     * 
     * @return void
     * @param Html $html
     * @param array[string]mixed &$get
     * @param Db $db
     */
    public function __construct($html, &$get, $db)
    {
        $this->_html = $html;
        $this->_get = $get;
        $this->_db = $db;
        $this->_pageTitle = 'A Memory Tree';
        $this->_style = array(
            '/css/screen.css'
        );
        $this->_script = array(
            'http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js',
            '/main.js',
            '/external.js'
        );
        $this->showNormalHeader();
        $this->showLeftBar();
        $this->showAdBar();
    }
    /**
     * Render the head of the page
     *
     * @return string
     * @param string $title
     */
    private function head()
    {
        $html = $this->_html;
        $title = $this->_pageTitle;
        $styles = '';
        foreach ($this->_style as $style) {
            $styles .= '<link rel="stylesheet" type="text/css" href="'.$style.'" />'."\n";
        }
        $scripts = '';
        foreach ($this->_script as $script) {
            $scripts .= '<script type="text/javascript" src="'.$script.'"> </script>'."\n";
        }
        return <<< EOT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>$title</title>
$styles
$scripts
    <script type="text/javascript">
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
    </script>
    <script type="text/javascript">
    try {
    var pageTracker = _gat._getTracker("UA-6903678-1");
    pageTracker._trackPageview();
    } catch(err) {}
    </script>
    <!--[if IE 6]>
    <link rel="stylesheet" type="text/css" ref="/css/iestyle.css" />
    <![endif]-->
</head>
<body>
    <div id="maincontainer">

EOT;
    }
    /**
     * Render the top bar of the page
     *
     * @return string
     * @param string $title
     */
    private function topBar()
    {
        $topBarClass = 'topbar';
        if (!empty($this->_showPersonalHeader)) {
            $topBarClass = 'topbar2';
        }
        return <<< EOT
<div id="$topBarClass">
    <ul>
        <li><a href="/index.php" title="">Home</a>|</li>
        <li><a href="/aboutus.php" title="About Us">About Us</a>|</li>
        <li><a href="/feesandservices.php" title="">Our Services</a>|</li>
        <li><a href="/faq.php" title="FAQ">FAQ</a></li>
    </ul>
</div>

EOT;
    }
    /**
     * Give the persons name
     *
     * @return string
     */
    private function personsName()
    {
        $html = $this->_html;
        $get = $this->_get;
        $db = $this->_db;
        if (!empty($get['personid'])) {
            $sql = <<< EOT
            SELECT
                Person.Surname, 
                Person.FirstNames 
            FROM Person 
            WHERE Person.ID = %d
EOT;
            $sql = sprintf($sql, intval($get['personid']));
            $result = $db->query($sql);
            if ($db->rowCount($result) > 0) {
                $row = $db->fetch($result);
                $firstNames = $db->unescape($row['FirstNames']);
                $lastName = $db->unescape($row['Surname']);
                $fullName = $html->text($firstNames.' '.$lastName);
            }
        }
        return $fullName;
    }
    private function todaysDate()
    {
        date_default_timezone_set('Pacific/Auckland');
        $todaysDate = date('l, F d, Y');
        return <<< EOT
        <span class="todaysDate">$todaysDate</span>
EOT;
    }
    private function getPersonCount()
    {
        $db = $this->_db;
        $personCount = 0;
        $sql = "SELECT count(*) AS count FROM Person";
        $result = $db->query($sql);
        if ($db->rowCount($result) > 0) {
            $row = $db->fetch($result);
            $personCount = intval($row['count']);
        }
        return $personCount;
    }
    private function totalNames()
    {
        $count = $this->getPersonCount();
        $totalNames = number_format($count, 0, '', ',');
        return 'There are <strong>'.$totalNames.'</strong> names to search today.';
    }
    private function actionAlert()
    {
        return <<< EOT
    <div class="actionAlert">
        <p>
			<span class="new">&nbsp;</span>
			Looking for someone?
		</p>
        <h3><a href="/alerts.php">Book an Email Alert</a></h3>
    </div>

EOT;
    }
    /**
     * Render a personal header for the page
     *
     * @return string
     */
    private function header()
    {
		$todaysDate = $this->todaysDate();
		$actionAlert = $this->actionAlert();
        $header = '';
        if ($this->_showPersonalHeader) {
			$fullName = $this->personsName();
            $header = <<< EOT
<div id="header" class="personal">
	<h1><a href="#" title="Home">A Memory Tree.co.nz - a lifetime of memories</a></h1>
	<h3>In Memory of</h3>
	<h2>$fullName</h2>
	<p class="status">$todaysDate</p>
$actionAlert
</div>

EOT;
        } else {
			$totalNames = $this->totalNames();
            $header = <<< EOT
<div id="header">
    <h1><a href="index.php" title="Home">A Memory Tree.co.nz - a lifetime of memories</a></h1>
    <p class="status">$totalNames $todaysDate</p>
$actionAlert
</div>

EOT;
        }
        return $header;
    }
    /**
     * Render the navigation of the page
     *
     * @return string
     * @param string $title
     */
    private function navigation()
    {
        return <<< EOT
<ul id="navigation">
    <li><span class="new">&nbsp;</span><a href="/alerts.php">Alerts</a></li>
    <li><a href="/travel.php">Travel</a></li>
    <li><a href="/donate_to_charity.php">Donate</a></li>
    <li><a href="/gift_giving.php">Gifts</a></li>
    <li><a href="/message_library.php">Library</a></li>
    <li><a href="/customs.php">Customs</a></li>
    <li><a href="/support.php">Support</a></li>
    <li><a href="/resources.php">Resources</a></li>
    <li><a href="/news.php">News</a></li>
    <li><a href="/feedback.php">Feedback</a></li>
</ul>

EOT;
    }
    private function getPublications() {
        $db = $this->_db;
        $html = $this->_html;
        $get = $this->_get;
        $sql = "Select ID, ShortName, Name from Newspapers ORDER BY Name ASC";
        $result = $db->query($sql);
        $publication = '';
        if (!empty($get['publication'])) {
            $publication = (string)$get['publication'];
        }
        $publications = '';
        $n = $db->rowCount($result);
        for ($i = 0; $i < $n; $i++) {
            $row = $db->fetch($result);
            $selected = '';
            if ($row['ShortName'] === $publication) {
                $selected = ' selected="selected"';
            }
            $shortName = $html->text($row['ShortName']);
            $name = $html->text($row['Name']);
            $publications .= <<< EOT
                        <option$selected value="$shortName">$name</option>

EOT;
        }
        return $publications;
    }
    private function members()
    {
        if (empty($_SESSION['user'])) {
            $left = '<a href="aboutMembers.php">what\'s this?</a>';
            $right = '<a href="/member.php">Login</a>';
        } else {
            $left = '<a href="/member.php">Member Page</a>';
            $right = '<a href="member.php?logout=yes">Logout</a>';
        }
        return <<< EOT
            <li class="memberpanel">
                <h3>Members</h3>
                <p><span>$left</span> $right</p>
            </li>

EOT;
    }
    private function searchPeople()
    {
        return <<< EOT
        <li>
            <h3>Search Names</h3>
            <form action="/searchpeople.php" method="get" onsubmit="return verifypeople(this)">
                <p>
                    <label>&nbsp;</label>
                    <input name="firstname" id="firstname" value="First Name" onfocus="removeText(this)"  onblur="resetText(this)" />
                </p>
                <p>
                    <label>*</label>
                    <input id="surname" name="surname" value="Last Name" onfocus="removeText(this)"  onblur="resetText(this)" />
                </p>
                <p>
                    <label class="reqnote">* required</label>
                    <input type="submit" class="gobutton" value="go" />
                </p>
            </form>
        </li>

EOT;
    }
    private function searchNewspapers()
    {
        $html = $this->_html;
        $get = $this->_get;
        $publications = $this->getPublications();
        $fromDate = 'From - dd/mm/yyyy';
        if (!empty($get['from'])) {
            $fromDate = $html->text($get['from']);
        }
        $toDate = 'To - dd/mm/yyyy';
        if (!empty($get['to'])) {
            $toDate = $html->text($get['to']);
        }
        return <<< EOT
        <li>
            <h3>Search Newspapers</h3>
            <form action="/searchpublications.php" method="get" onsubmit="return verifypublication(this)">
                <p>
                    <label>*</label>
                    <select>
                        <option>Notice Type</option>
                        <option selected="selected">Death Notices</option>
                    </select>
                </p>
                <p>
                    <label>*</label>
                    <select>
                        <option>Country</option>
                        <option selected="selected">New Zealand</option>
                    </select>
                </p>
                <p>
                    <label>*</label>
                    <select name="publication" id="publication">
                        <option>Publication</option>
                        $publications
                    </select>
                </p>
                <p>
                    <label>*</label>
                    <input name="from" id="from" value="$fromDate" onfocus="removeText(this)" onblur="resetText(this)" 
                    onkeyup="javascript:
                        if(this.value.length==2 || this.value.length==5){
                        if(this.value.charAt(this.value.length-1)=='/'){
                            if(this.value.length==2){
                                this.value='0'+this.value.substring(0,this.value.length-1)
                            }else if(this.value.length==5){
                                this.value=this.value.substring(0,3)+'0'+this.value.substring(3,this.value.length-1)
                            }
                        }
                        this.value=this.value+'/';
                        }
                        if(this.value.length == 7){
                            if(this.value.charAt(6)!=2){
                                this.value=this.value.substring(0,6)+'20'+this.value.substr(6);
                            }
                        }
                        if(this.value.length > 10){this.value=this.value.substring(0,10);}
                        "
                    />
                </p>
                <p>
                    <label>*</label>
                    <input name="to" id="to" value="$toDate" onfocus="removeText(this)" onblur="resetText(this)" 
                    onkeyup="javascript:
                        if(this.value.length==2 || this.value.length==5){
                        if(this.value.charAt(this.value.length-1)=='/'){
                            if(this.value.length==2){
                                this.value='0'+this.value.substring(0,this.value.length-1)
                            }else if(this.value.length==5){
                                this.value=this.value.substring(0,3)+'0'+this.value.substring(3,this.value.length-1)
                            }
                        }
                        this.value=this.value+'/';
                        }
                        if(this.value.length == 7){
                            if(this.value.charAt(6)!=2){
                                this.value=this.value.substring(0,6)+'20'+this.value.substr(6);
                            }
                        }
                        if(this.value.length > 10){this.value=this.value.substring(0,10);}
                        "
                    />
                </p>
                <p>
                    <label class="reqnote">* required</label>
                    <input type="submit" class="gobutton" value="go"/>
                </p>
            </form>
        </li>

EOT;
    }
    private function otherLinks()
    {
        return <<< EOT
        <li class="linkitem">
            <a href="/news.php" title="News">News</a>
        </li>
        <li class="linkitem">
            <a href="/feedback.php" title="Place and View Feedback">Feedback</a>
        </li>
        <li class="alt">
            <h3>Follow us on</h3><br />
            <a title="Follow us on Twitter" class="browsernav_twitter" href="http://twitter.com/amemorytree"> Twitter</a>
        </li>

EOT;
    }
    private function tellAFriend()
    {
        return <<< EOT
        <li class="alt">
            <a title="Tell a Friend" class="browsernav_tellfriend" href="mailto:?subject=I wanted to tell you about this website&amp;body=Hi, I wanted to tell you about this website http://www.amemorytree.co.nz Visit the site today and check out some of the features including being able to leave a message on someone's Remembrance Page, see if a lawyer is looking for you and locate which death notices appear in what NZ daily newspapers.">Tell a Friend</a>
            <br/>
        </li>

EOT;
    }
    /**
     * Render the left bar of the page
     *
     * @return string
     * @param string $title
     */
    private function leftBar()
    {
        if (empty($this->_showLeftBar)) {
            return '';
        }
        $members = $this->members();
        $searchPeople = $this->searchPeople();
        $searchNewspapers = $this->searchNewspapers();
        $otherLinks = $this->otherLinks();
        $tellAFriend = $this->tellAFriend();
        return <<< EOT
<div id="contentarea">
    <ul id="leftbar">
$members
$searchPeople
$searchNewspapers
$otherLinks
$tellAFriend
    </ul>
EOT;
    }
    /** Render the ad bar
     *
     * @return string
     */
    private function adBar()
    {
        if (empty($this->_showAdBar)) {
            return '';
        }
        return <<< EOT
<ul id="adbar">
<!--
    <li id="createbox">
        <h2>Create a Memory Book</h2>
        <p>Start Your Own Today</p>
        <a href="#" title="">More Information</a>
    /li>
-->
    <li class="adverttitle">-- Advertisement --</li>
    <li class="advert">
        <script type="text/javascript">
        <!--
        google_ad_client = "pub-9493103608981110";
        /* 120x600, created 1/23/09 */
        google_ad_slot = "8479916595";
        google_ad_width = 120;
        google_ad_height = 600;
        //-->
        </script>
        <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
    </li>
</ul>
</div>

EOT;
    }
    /**
     * Convert a date string to a formatted date, or an empty string for no date
     * 
     * @param string $date The date value to convert
     * @return string      The converted date, or an empty string when no date
     */
    private function featuringDateFormat($date)
    {
        if ($date === '0000-00-00 00:00:00') {
            return '';
        } else {
            return date('d/m/Y', strtotime($date));
        }
    }
    /**
     * Trim text to a maximum whole word length
     *
     * @param string $text
     * @param int $length
     * @return string
     */
    private function trimWholeWordLength($text, $length) {
        $end = strrpos(substr($text, 0, $length), ' ');
        return substr($text, 0, $end);
    }
    /**
     * Provide 60 characters, and cut back to nearest word
     * 
     * @param string $blurb The blurb to be changed
     * @param int $personId The persons id number
     * @return string       The converted name
     */
    private function formatBlurbDetails($blurb)
    {
        $limit = 60;
        $blurb = $this->trimWholeWordLength($blurb, $limit);
        return $blurb;
    }
    /**
     * Retrieve from the database a set group of featured people
     * 
     * @return array[string]string
     * @param int $index
     */
    private function getFeaturedPerson($index)
    {
        $db = $this->_db;
        $person = array(
            'id' => '',
            'blurb' => '',
            'position' => '',
            'deathDate' => '',
            'lastName' => '',
            'firstNames' => ''
        );
        $sql = <<< EOT
            SELECT
                FeaturingPerson.Blurb,
                FeaturingPerson.PersonID,
                FeaturingPerson.Position,
                Person.DeathDate,
                Person.Surname,
                Person.FirstNames
            FROM
                FeaturingPerson
                    LEFT OUTER JOIN Person
                         ON FeaturingPerson.PersonID = Person.ID
            WHERE
                Position = %d
            ORDER BY
                Position ASC
EOT;
        $sql = sprintf($sql, $index);
        $result = $db->query($sql);
        while (TRUE) {
            $row = $db->fetch($result);
            if (empty($row)) {
                break;
            }
            $person['id'] = $row['PersonID'];
            $person['blurb'] = $row['Blurb'];
            $person['position'] = $row['Position'];
            $person['deathDate'] = $row['DeathDate'];
            $person['lastName'] = $row['Surname'];
            $person['firstNames'] = $row['FirstNames'];
        }
        return $person;
    }
    /** Render the feature bar
     *
     * @return string
     */
    private function featureBar()
    {
        $html = $this->_html;
        if (empty($this->_showFeatureBar)) {
            return '';
        }
        $majorFeatures = '';
        for ($i = 0; $i < 4; $i++) {
            $person = $this->getFeaturedPerson($i);
            $classname = '';
            if ($i === 0) {
                $classname = ' class="topitem"';
            } else if ($i === 3) {
                $classname = ' class="bottomitem"';
            }
            $personId = intval($person['id']);
            $image = '/images/featuring/'.$personId.'.jpg';
            $image = $html->text($image);
            $firstnames = $html->text($person['firstNames']);
            $lastname = $html->text($person['lastName']);
            $deathdate = $html->text($this->featuringDateFormat($person['deathDate']));
            $blurb = $html->text($this->formatBlurbDetails($person['blurb']));
            if (!file_exists($_SERVER['DOCUMENT_ROOT'].$image)) {
                $image = '/images/assets/placeholderphoto.gif';
            }
            $majorFeatures .= <<< EOT
        <li$classname>
            <a href="remembrance.php?personid=$personId"><img alt="" style="width:115px;" src="$image" /></a>
            <h4><a href="remembrance.php?personid=$personId">$firstnames $lastname</a></h4>
            <p>$deathdate<br />
               <a href="remembrance.php?personid=$personId">$blurb ...</a></p>
        </li>

EOT;
        }
        $minorFeatures = '';
        for ($i = 4; $i < 10; $i++) {
            $person = $this->getFeaturedPerson($i);
            $personId = intval($person['id']);
            $firstName = $person['firstNames'];
            $lastName = $person['lastName'];
            $minorFeatures .= '<li><a href="remembrance.php?personid='.$personId.'">'.$firstName.' '.$lastName.'</a></li>';
        }
        return <<< EOT
<div id="featuredbar">
    <div class="topbox">
        <h2>Featuring...</h2>
        <p>Click to view details and leave an entry</p>
    </div>
    <ul>
$majorFeatures
    </ul>
    <div class="bottombox">
        <ul>
$minorFeatures
        </ul>
        <a href="featuringhistory.php" title="Previously featured">Previously featured</a>
    </div>
</div>

EOT;
    }
    /** Render the bottom box
     *
     * @return string
     */
    private function bottomBox()
    {
        return <<< EOT
<ul id="bottombox">
    <li><img src="images/assets/bottombanner.jpg" alt="" /></li>
    <li class="rightside"><img src="images/assets/bottombanner.jpg" alt="" /></li>
</ul>
<ul>
    <li><p>Images courtesy of <a href="http://www.dreamstime.com">Dreamstime.com</a>. Clip Art courtesy of <a href="http://www.graphicsfactory.com">Graphicsfactory.com.</a></p></li>
</ul>

EOT;
    }
    /** Render the footer
     *
     * @return string
     */
    private function footer()
    {
        return <<< EOT
<div id="footer">
    <ul>
        <li><a href="/terms.php" title="Terms" >Terms</a>|</li>
        <li><a href="/privacy.php" title="Privacy" >Privacy</a>|</li>
        <li><a href="/codeofethics.php" title="Code of Ethics" >Code of Ethics</a>|</li>
        <li><a href="/safety.php" title="Safety Tips" >Safety Tips</a>|</li>
        <li><a href="/aboutus.php" title="About Us" >About Us</a>|</li>
        <li><a href="/contactus.php" title="Contact" >Contact</a>|</li>
        <li><a href="/advertise.php" title="Advertise" >Advertise</a>|</li>
    </ul>
</div>
<p class="copyright">&copy; A Memory Tree Limited 2006-2009. This site contains copyright sensitive material and cannot be reproduced without written consent from copyright holders. - Patent Pending -</p>

EOT;
    }
    /** Render the end body
     *
     * @return string
     */
    private function endBody()
    {
        return <<< EOT
	</div>
</body>
</html>

EOT;
    }
    /**
     * Return the page contents
     * 
     * @return string
     */
    public function renderTop()
    {
        $page = '';
        $page .= $this->head();
        $page .= $this->topBar();
        $page .= $this->header();
        $page .= $this->navigation();
        $page .= $this->leftBar();
        return $page;
    }
    /**
     * Return the page contents
     * 
     * @return string
     */
    public function renderBottom()
    {
        $page = '';
        $page .= $this->featureBar();
        $page .= $this->adBar();
        $page .= $this->bottomBox();
        $page .= $this->footer();
        $page .= $this->endBody();
        return $page;
    }
    /**
     * Return the page contents
     * 
     * @return string
     * @param string $content
     */
    public function render($content='')
    {
        $this->style('/css/normal.css');
        $page = '';
        $page .= $this->renderTop();
        $page .= $content;
        $page .= $this->renderBottom();
        return $page;
    }
}
?>
